<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>新型肺炎确诊患者相同行程查询 1.0</title>
  <script type="text/javascript" src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
  <script type="text/javascript" src="./static/xlsx.core.min.js"></script>
  <link rel="stylesheet" href="./static/layui/css/layui.css">
  <style>
    body {
      margin: 20px;
    }
    header {
      padding-bottom: 10px;
      text-align: center;
    }
    h2 {
      margin: 0;
      color: gray;
    }
    #update_at {
      padding: 10px;
    }
    .info {
      vertical-align: middle;
      color: gray;
      font-size: 12px;
      margin-left: 10px;
    }
    #no_data_info {
      text-align: center;
      color: rgb(55, 182, 77);
    }
    #excel_data td {
      padding: 0 5px;
    }
    #excel_name {
      color: cornflowerblue;
    }
    .excel_table {
      width: 400px;
    }
    .ps_info {
      color: grey;
      margin-bottom: 20px;
    }
  </style>
</head>
<body>
  <header>
    <h2>新型肺炎确诊患者同行程查询</h2>
    <div id="update_at"></div>
  </header>

  <!-- 上传文件按钮 -->
  <input type="file" id="excel-file" style="display: none;">
  <button class="layui-btn layui-btn-radius layui-btn-primary" onclick="document.getElementById('excel-file').click()">点击上传Excel表格</button>
  <span class="info">注：表格请至少包含三列内容：姓名 / 日期 / 车次</span>

  <!-- 表格 -->
  <table class="layui-table">
    <colgroup>
      <col width="120">
    </colgroup>
    <thead id="thead"></thead>
    <tbody id="tbody"></tbody>
  </table>
  <p id="no_data_info">暂无同行数据</p>

  <!-- 表格数据预览 -->
  <p>Excel表格数据预览 <span id="excel_name"></span></p>
  <table class="layui-table excel_table">
    <tbody id="excel_data">
  </table>

  <!-- 注 -->
  <p class="ps_info">注：如果时间出现 NaN-NaN-NaN，需要在Excel内双击对应数据，使之单元格格式变为时间格式，方可生效。</p>

  <!-- 友链 -->
  <p>同行程查询地址数据源</p>
  <p>1. <a href="http://2019ncov.nosugartech.com/" target="_blank">新型冠状病毒肺炎，确诊患者同行程查询工具</a></p>
  <p>2. <a href="https://rl.inews.qq.com/h5/trip?from=newsapp" target="_blank">腾讯新闻疫情地图</a></p>
  
  <script type="text/javascript" src="./static/layui/layui.all.js"></script>
  <script type="text/javascript" src="./static/utils.js"></script>

  <!-- 枚举 -->
  <script>
    let cols = [
      {name: '同事姓名', type: 'pName', width: 130},
      {name: '同事时间', type: 'pDate', width: 130},
      {name: '同事班次', type: 'pNo', width: 130},
      {name: '风险日期', type: 't_date'},
      {name: '风险车次/车牌/航班/场所名', type: 't_no'},
      {name: '出行类型', type: 't_type'},
      {name: '始发站', type: 't_pos_start'},
      {name: '到达站', type: 't_pos_end'},
      {name: '车厢', type: 't_no_sub'},
      {name: '描述', type: 't_memo'},
      {name: '更新时间', type: 'updated_at'},
    ]
    let tTypes = {
      1: '飞机',
      2: '火车',
      3: '地铁',
      4: '长途客车/大巴',
      5: '公交车',
      6: '出租车',
      7: '轮船',
      8: '其它公共场所',
    }
    let tr = document.createElement('tr');
    for(let k=0; k<cols.length; k++) {
      let th = document.createElement('th');
      th.innerText = cols[k].name;
      tr.append(th);
    }
    document.getElementById('thead').append(tr);
  </script>
  <!-- 获取网络数据 -->
  <script>
    let url = "/data.json?"+Math.floor(new Date().getTime()/1000/3600);
    url="http://2019ncov.nosugartech.com" + url;
    let AllData = null;
    $.getJSON(url, function (result) {
      console.log('data', result);
      AllData = result.data;
      let tmpt = 0;
      AllData.forEach(element => {
        tmpt = Math.max(tmpt,new Date(element.updated_at).getTime());
      });
      let refreshTime = dateformat(new Date(tmpt),'yyyy-MM-dd hh:mm');
      console.log('数据更新时间:', refreshTime);
      $("#update_at").html('数据更新时间：'+dateformat(new Date(tmpt),'yyyy-MM-dd hh:mm'));
    });
  </script>
  <!-- 对比表格数据跟网络数据 -->
  <script>
    function handleData(persons) {
      if (!AllData) {
        alert('未获取到网络上的行程数据！');
        return;
      }
      if (!persons) {
        alert('表格无内容或文件错误！');
        return;
      }
      if (!persons[0]['姓名'] || !persons[0]['日期'] || !persons[0]['车次']) {
        alert('表格内数据结构有误，结果可能不准确~');
      }
      let warningPersons = [];
      $('#excel_data').html('');
      for(let i=0; i<persons.length; i++) {
        let person = persons[i],
        pName = person['姓名'],
        pDate = excelDateFormat(person['日期'], '-'),
        pDateGetTime = new Date(pDate).getTime(),
        pNo = person['车次'].toUpperCase();
        console.log(pName, pDate, pNo)
        let tr = document.createElement('tr');
        tr.innerHTML = `<td>${pName}</td><td>${pDate}</td><td>${pNo}</td>`;
        $('#excel_data').append(tr);
        for(let k=0; k<AllData.length; k++) {
          let item = AllData[k];
          if (pDateGetTime == new Date(item.t_date).getTime() // 相同日期
              && (item.t_no == pNo || (item.t_no.indexOf(pNo) > -1) ) // 相同车次或航班或小区
          ) {
            warningPersons.push({
              pName,
              pDate,
              pNo,
              ...item,
            })
            tr.style.color = 'red';
          }
        }
      }
      console.log('warningPersons', warningPersons);

      // 插入表格
      document.getElementById('tbody').innerHTML = '';
      if (warningPersons.length) {
        $('#no_data_info').hide();
        for(let i=0; i<warningPersons.length; i++) {
          let person = warningPersons[i];
          let tr = document.createElement('tr');
          for(let k=0; k<cols.length; k++) {
            let td = document.createElement('td');
            td.innerText = person[cols[k].type];
            tr.append(td);
          }
          document.getElementById('tbody').append(tr);
        }
      } else {
        $('#no_data_info').show();
      }
      $('#excel-file').val(null);
    }
  </script>
  <!-- 上传Excel表格 -->
  <script>
    $('#excel-file').change(function(e) {
        console.log(e.target.files)
        let files = e.target.files;

        let fileReader = new FileReader();
        fileReader.onload = function(ev) {
            try {
                var data = ev.target.result,
                    workbook = XLSX.read(data, {
                        type: 'binary'
                    }), // 以二进制流方式读取得到整份excel表格对象
                    persons = []; // 存储获取到的数据
            } catch (e) {
                console.log('文件类型不正确');
                return;
            }

            // 表格的表格范围，可用于判断表头是否数量是否正确
            let fromTo = '';
            // 遍历每张表读取
            for (let sheet in workbook.Sheets) {
                if (workbook.Sheets.hasOwnProperty(sheet)) {
                    fromTo = workbook.Sheets[sheet]['!ref'];
                    console.log(fromTo);
                    persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                    // break; // 如果只取第一张表，就取消注释这行
                }
            }

            console.log(persons);
            handleData(persons);
        };

        // 以二进制方式打开文件
        fileReader.readAsBinaryString(files[0]);
        $('#excel_name').html(files[0].name)
    });
  </script>
</body>
</html>